﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using ARR.Entities;
using ARR.DataModel.Repositories;
using System.Data;
using ARR.DataModel.Gateways;
using ARR.Shared;
using System.Data.SqlClient;
using System.Transactions;
using System.Text.RegularExpressions;

namespace ARR.Services.Domain.Importers
{
    public class CanadaImporter
    {
        public Country Country
        {
            get
            {
                var country = CountriesRepository.Select(c => c.Code == Constants.CountryCode.Canada).SingleOrDefault();
                return new Country(country);
            }
        }

        public List<ColumnFormat> CanadaColumns
        {
            get
            {
                return new List<ColumnFormat>()
                {
                   new ColumnFormat{ColumnIndex = 0, ColumnName = "Store", ColumnLength = 6},
                   new ColumnFormat{ColumnIndex = 1, ColumnName = "Prov", ColumnLength = 31},
                   new ColumnFormat{ColumnIndex = 2, ColumnName = "cMonth", ColumnLength = 7},
                   new ColumnFormat{ColumnIndex = 3, ColumnName = "UPC", ColumnLength = 26},
                   new ColumnFormat{ColumnIndex = 4, ColumnName = "Description", ColumnLength = 61},
                   new ColumnFormat{ColumnIndex = 5, ColumnName = "Category", ColumnLength = 10},
                   new ColumnFormat{ColumnIndex = 6, ColumnName = "SubCat", ColumnLength = 10},
                   new ColumnFormat{ColumnIndex = 7, ColumnName = "Brand", ColumnLength = 10},
                   new ColumnFormat{ColumnIndex = 8, ColumnName = "Format", ColumnLength = 10},
                   new ColumnFormat{ColumnIndex = 9, ColumnName = "UOM", ColumnLength = 5},
                   new ColumnFormat{ColumnIndex = 10, ColumnName = "Sales", ColumnLength = 41},
                   new ColumnFormat{ColumnIndex = 11, ColumnName = "SKU_Quan", ColumnLength = 41},
                   new ColumnFormat{ColumnIndex = 12, ColumnName = "Sales_Amount", ColumnLength = 41},
                   new ColumnFormat{ColumnIndex = 13, ColumnName = "Cost_Amount", ColumnLength = 41},
                   new ColumnFormat{ColumnIndex = 14, ColumnName = "Margin", ColumnLength = 41, IsLastColumn = true},
                };
            }
        }

        public IList<ImporterResult> ImportArticleMasterStep1()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                //Check Prerequisites
                //1. Chequeo que estén los archivos
                string sourceDirectoryPath = ImporterHelper.GetArticleMasterFilePath(Country, "Range Review I");
                string[] files = Directory.GetFiles(sourceDirectoryPath);

                if (files.Length == 0)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.PreRequisites,
                        Description = "There are no Sales files to import in the server directory.",
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }
                if (files.Length > 1)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.PreRequisites,
                        Description = "There should be ONLY ONE SALES file to import in the server directory.",
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }


                //SALES
                foreach (string file in files)
                {
                    string line;
                    Dictionary<string, string> fields;
                    int row = 1;
                    using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default, true))
                    {
                        line = sr.ReadLine();
                        
                        if (!line.Equals("Store Prov                           cMonth UPC                       Description                                                  Category  SubCat    Brand     Format    UOM  Sales                                    SKU_Quan                                 Sales_Amount                             Cost_Amount                              Margin                                   "))
                        {
                            count++;
                            importerResults.Add(new ImporterResult
                            {
                                Category = ResultCategory.PreRequisites,
                                Description = string.Format("Row {0} in file {1} is incorrect. The headers are not in the correct format.", row, file),
                                ErrorType = ErrorType.Error,
                                Id = count
                            });
                        }

                        line = sr.ReadLine();
                        row++;
                        if (!line.StartsWith("----") && !line.StartsWith("|---") && !line.StartsWith(" ---"))
                        {
                            count++;
                            importerResults.Add(new ImporterResult
                            {
                                Category = ResultCategory.PreRequisites,
                                Description = string.Format("Row {0} in file {1} is incorrect.", row, file),
                                ErrorType = ErrorType.Error,
                                Id = count
                            });
                        }

                        //TODO: Chequear algun valor de la primer linea que me asegure que el file es el del pais correcto.
                        line = sr.ReadLine();
                        row++;
                        fields = ImporterHelper.GetFieldsFromFixedColumnLine(line, CanadaColumns);
                        string upc = fields["UPC"];

                    }
                }
            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.PreRequisites,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        private string[] SplitByWidth(string s, int[] widths)
        {
            string[] ret = new string[widths.Length];
            char[] c = s.ToCharArray();
            int startPos = 0;
            for (int i = 0; i < widths.Length; i++)
            {
                int width = widths[i];
                ret[i] = new string(c.Skip(startPos).Take(width).ToArray<char>());
                startPos += width;
            }
            return ret;
        }

        private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled);
        const string REGEX_LOT = "^(?<Store>.{6})" + "(?<Prov>.{31})" + "(?<cMonth>.{7})" + "(?<UPC>.{26})" + "(?<Description>.{61})"
            + "(?<Category>.{10})" + "(?<SubCat>.{10})" + "(?<Brand>.{10})" + "(?<Format>.{10})" + "(?<UOM>.{10})";

        public IList<ImporterResult> ImportArticleMasterStep2()
        {
            //TODO: A futuro parametrizar el Culture en el objeto Range Review o en el Country
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            string currentLine = string.Empty;
            int row = 0;
            
            try
            {
                // Limpio las tablas temporales [TempArticles].
                TempArticlesRepository.TruncateTable();

                string sourceDirectoryPath = ImporterHelper.GetArticleMasterFilePath(Country, "Range Review I");
                string[] files = Directory.GetFiles(sourceDirectoryPath);

                //int[] widths = { 6, 31, 7, 26, 61, 10, 10, 10, 10, 5, 41, 41, 41, 41, 41 }; //Hasta el final
                int[] widths = { 6, 31, 7, 26, 61, 10, 10, 10, 10, 5}; //Hasta UOM

                //Articles
                foreach (string file in files)
                {
                    DataTable sourceTable = ImporterHelper.CreateDataTableFromGateway<TempArticleRow>();

                    string[] lines = File.ReadAllLines(file);
                    
                    foreach (var line in lines)
                    {
                        row++;
                        currentLine = line;

                        if (!line.StartsWith("Store Prov ") && !line.StartsWith("-----") && !string.IsNullOrWhiteSpace(line.Trim()))
                        {
                            //Opcion 1: usando regex
                            Match match = reLot.Match(line);

                            DataRow datarow = sourceTable.NewRow();
                            datarow["CountryId"] = Country.Id;
                            datarow["CategoryId"] = 1;
                            datarow["Code"] =  match.Groups["UPC"].Value;
                            datarow["Name"] = match.Groups["Description"].Value;
                            datarow["EAN"] = match.Groups["UPC"].Value;
                            datarow["UOM"] = match.Groups["UOM"].Value;
                            datarow["Brand"] = match.Groups["Brand"].Value;
                            datarow["Manufacturer"] = string.Empty;
                            sourceTable.Rows.Add(datarow);

                            ////Opcion 2: usando linq (aca me llevó 7 minutos procesar el archivo de 20 megas
                            //string[] fields = SplitByWidth(line, widths);
                            
                            //if (fields.Length != 10) //TODO: mejorar esto porque me sigue guardando en la base la ultima linea de texto
                            //    continue;

                            //DataRow datarow = sourceTable.NewRow();
                            //datarow["CountryId"] = Country.Id;
                            //datarow["CategoryId"] = 1;
                            //datarow["Code"] = fields[3];
                            //datarow["Name"] = fields[4];
                            //datarow["EAN"] = fields[3];
                            //datarow["UOM"] = fields[9];
                            //datarow["Brand"] = fields[7];
                            //datarow["Manufacturer"] = string.Empty;
                            //sourceTable.Rows.Add(datarow);
                        }
                    }

                    //TODO: Descrubir categoryId del articulo corriendo un Update

                    // new method: SQLBulkCopy:
                    TempArticlesRepository.BulkCopy(sourceTable);
                }

            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.TemporalTable,
                    Description = string.Format("Row Number: {0}, Line: {1}, Message: {2}", row, currentLine, ex.Message),
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }
        public IList<ImporterResult> ImportArticleMasterStep3()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                //Verifico si hay Articulos sin Codigo de barras.
                List<TempArticleRow> articles = TempArticlesRepository.Select(art => art.EAN == null || art.EAN == "" || art.EAN == " ");

                List<TempArticleRow> articlesMan = TempArticlesRepository.Select(art => art.Manufacturer == null || art.Manufacturer == "");

                foreach (TempArticleRow art in articles)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.Validation,
                        Description = string.Format(Errors.TheArticleDoesntHaveEAN, art.Name),
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }

                //TODO: Agregar aqui todas las validaciones necesarias para el Maestro de Articulos
            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.Validation,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportArticleMasterStep4()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    //Hago Update de MARA
                    ArticlesRepository.UpdateFromTempArticle(Country.Id);

                    //Hago Insert de MARA
                    ArticlesRepository.InsertFromTempArticles(Country.Id);

                    scope.Complete();
                }

                //Borro las tablas temporales
                TempArticlesRepository.TruncateTable();

                //Muevo los archivos a la carpeta Old
                string sourceDirectoryPath = ImporterHelper.GetArticleMasterFilePath(Country, "Range Review I");
                ImporterHelper.MoveImportedFilesAndWriteLog(Country, sourceDirectoryPath);
            }
            catch (Exception ex)
            {
                count++;

                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.Updating,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }


        public IList<ImporterResult> ImportStoreMasterStep1()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                //Check Prerequisites
                //1. Chequeo que estén los archivos
                string sourceDirectoryPath = ImporterHelper.GetStoreMasterFilePath(Country);
                string[] files = Directory.GetFiles(sourceDirectoryPath);

                if (files.Length == 0)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.PreRequisites,
                        Description = "There are no Sales files to import in the server directory.",
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }
                if (files.Length > 1)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.PreRequisites,
                        Description = "There should be ONLY ONE SALES file to import in the server directory.",
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }


                //SALES
                foreach (string file in files)
                {
                    string line;
                    Dictionary<string, string> fields;
                    int row = 1;
                    using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default, true))
                    {
                        line = sr.ReadLine();

                        if (!line.Equals("Store Prov                           cMonth UPC                       Description                                                  Category  SubCat    Brand     Format    UOM  Sales                                    SKU_Quan                                 Sales_Amount                             Cost_Amount                              Margin                                   "))
                        {
                            count++;
                            importerResults.Add(new ImporterResult
                            {
                                Category = ResultCategory.PreRequisites,
                                Description = string.Format("Row {0} in file {1} is incorrect. The headers are not in the correct format.", row, file),
                                ErrorType = ErrorType.Error,
                                Id = count
                            });
                        }

                        line = sr.ReadLine();
                        row++;
                        if (!line.StartsWith("----") && !line.StartsWith("|---") && !line.StartsWith(" ---"))
                        {
                            count++;
                            importerResults.Add(new ImporterResult
                            {
                                Category = ResultCategory.PreRequisites,
                                Description = string.Format("Row {0} in file {1} is incorrect.", row, file),
                                ErrorType = ErrorType.Error,
                                Id = count
                            });
                        }

                        //TODO: Chequear algun valor de la primer linea que me asegure que el file es el del pais correcto.
                        line = sr.ReadLine();
                        row++;
                        fields = ImporterHelper.GetFieldsFromFixedColumnLine(line, CanadaColumns);
                        string upc = fields["UPC"];

                    }
                }
            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.PreRequisites,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportStoreMasterStep2()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                // Limpio las tablas temporales [TempStores].
                TempStoresRepository.TruncateTable();

                string sourceDirectoryPath = ImporterHelper.GetStoreMasterFilePath(Country);
                string[] files = Directory.GetFiles(sourceDirectoryPath);

                //Stores
                foreach (string file in files)
                {
                    string line;
                    Dictionary<string, string> fields;
                    int row = 0;

                    DataTable sourceTable = ImporterHelper.CreateDataTableFromGateway<TempStoreRow>();

                    using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default, true))
                    {
                        while (!sr.EndOfStream)
                        {
                            line = sr.ReadLine();
                            row++;
                            if (!line.StartsWith("Store Prov ") && !line.StartsWith("-----") && !string.IsNullOrWhiteSpace(line))
                            {
                                fields = ImporterHelper.GetFieldsFromFixedColumnLine(line, CanadaColumns);

                                if (fields.Count != 15)
                                {
                                    count++;
                                    importerResults.Add(new ImporterResult
                                    {
                                        Category = ResultCategory.TemporalTable,
                                        Description = string.Format(Errors.InvalidNumberOfFieldsInRow, row, file),
                                        ErrorType = ErrorType.Error,
                                        Id = count
                                    });
                                }

                                //TODO: Consultar de donde saco el nombre del store. Ahora le estoy clavando el codigo como nombre.
                                DataRow datarow = sourceTable.NewRow();
                                datarow["CountryId"] = Convert.ToInt16(Country.Id);
                                datarow["Code"] = fields["Store"];
                                datarow["Name"] = fields["Store"];
                                datarow["Region"] = fields["Prov"];

                                sourceTable.Rows.Add(datarow);
                            }
                        }
                    }

                    // new method: SQLBulkCopy:
                    TempStoresRepository.BulkCopy(sourceTable);
                }

            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.TemporalTable,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportStoreMasterStep3()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                //Verifico si hay tiendas sin Codigo o Nombre.
                List<TempStoreRow> storesWithoutCode = TempStoresRepository.Select(store => store.Code == null || store.Code == string.Empty);
                List<TempStoreRow> storesWithoutName = TempStoresRepository.Select(store => store.Name == null || store.Name == string.Empty);

                foreach (TempStoreRow store in storesWithoutCode)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.Validation,
                        Description = string.Format(Errors.StoreDoesntHaveCode, store.Name),
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }

                foreach (TempStoreRow store in storesWithoutName)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.Validation,
                        Description = string.Format(Errors.StoreDoesntHaveName, store.Code),
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }

                //TODO: Agregar aqui todas las validaciones necesarias para el Maestro de Tiendas
            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.Validation,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportStoreMasterStep4()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    //Hago Update de Maestro de Tiendas
                    StoresRepository.UpdateFromTempStores(Country.Id);

                    //Hago Insert de Maestro Tiendas
                    StoresRepository.InsertFromTempStores(Country.Id);

                    scope.Complete();
                }

                //Borro las tablas temporales
                TempStoresRepository.TruncateTable();

                //Muevo Archivos importados a la carpeta old y Loggeo la importacion.
                string sourceDirectoryPath = ImporterHelper.GetStoreMasterFilePath(Country);
                ImporterHelper.MoveImportedFilesAndWriteLog(Country, sourceDirectoryPath);
            }
            catch (Exception ex)
            {
                count++;

                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.Updating,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }


        public IList<ImporterResult> ImportArticleSalesStep1()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                //Check Prerequisites
                //1. Chequeo que estén los archivos
                string sourceDirectoryPath = ImporterHelper.GetStoreMasterFilePath(Country);
                string[] files = Directory.GetFiles(sourceDirectoryPath);

                if (files.Length == 0)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.PreRequisites,
                        Description = "There are no Sales files to import in the server directory.",
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }
                if (files.Length > 1)
                {
                    count++;
                    importerResults.Add(new ImporterResult
                    {
                        Category = ResultCategory.PreRequisites,
                        Description = "There should be ONLY ONE SALES file to import in the server directory.",
                        ErrorType = ErrorType.Error,
                        Id = count
                    });
                }


                //SALES
                foreach (string file in files)
                {
                    string line;
                    Dictionary<string, string> fields;
                    int row = 1;
                    using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default, true))
                    {
                        line = sr.ReadLine();

                        if (!line.Equals("Store Prov                           cMonth UPC                       Description                                                  Category  SubCat    Brand     Format    UOM  Sales                                    SKU_Quan                                 Sales_Amount                             Cost_Amount                              Margin                                   "))
                        {
                            count++;
                            importerResults.Add(new ImporterResult
                            {
                                Category = ResultCategory.PreRequisites,
                                Description = string.Format("Row {0} in file {1} is incorrect. The headers are not in the correct format.", row, file),
                                ErrorType = ErrorType.Error,
                                Id = count
                            });
                        }

                        line = sr.ReadLine();
                        row++;
                        if (!line.StartsWith("----") && !line.StartsWith("|---") && !line.StartsWith(" ---"))
                        {
                            count++;
                            importerResults.Add(new ImporterResult
                            {
                                Category = ResultCategory.PreRequisites,
                                Description = string.Format("Row {0} in file {1} is incorrect.", row, file),
                                ErrorType = ErrorType.Error,
                                Id = count
                            });
                        }

                        //TODO: Chequear algun valor de la primer linea que me asegure que el file es el del pais correcto.
                        line = sr.ReadLine();
                        row++;
                        fields = ImporterHelper.GetFieldsFromFixedColumnLine(line, CanadaColumns);
                        string upc = fields["UPC"];

                    }
                }
            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.PreRequisites,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportArticleSalesStep2()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                // Limpio las tablas temporales [TempArticleSales].
                TempArticleSalesRepository.TruncateTable();

                string sourceDirectoryPath = ImporterHelper.GetSalesFilePath(Country);
                string[] files = Directory.GetFiles(sourceDirectoryPath);

                //Cacheo en memoria los articles y los stores del pais.
                List<ArticleRow> Articles = ArticlesRepository.Select(art => art.CountryId == Country.Id);
                List<StoreRow> Stores = StoresRepository.Select(st => st.CountryId == Country.Id);
                StoreRow store = null;
                ArticleRow article = null;
                DateTime? date = null;
                //Sales
                foreach (string file in files)
                {
                    string line;
                    Dictionary<string, string> fields;
                    int row = 0;

                    DataTable sourceTable = ImporterHelper.CreateDataTableFromGateway<TempArticleSaleRow>();

                    using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default, true))
                    {
                        while (!sr.EndOfStream)
                        {
                            line = sr.ReadLine();
                            row++;
                            if (!line.StartsWith("Store Prov ") && !line.StartsWith("-----") && !string.IsNullOrWhiteSpace(line))
                            {
                                fields = ImporterHelper.GetFieldsFromFixedColumnLine(line, CanadaColumns);

                                if (fields.Count != 15)
                                {
                                    count++;
                                    importerResults.Add(new ImporterResult
                                    {
                                        Category = ResultCategory.TemporalTable,
                                        Description = string.Format(Errors.InvalidNumberOfFieldsInRow, row, file),
                                        ErrorType = ErrorType.Error,
                                        Id = count
                                    });
                                }

                                //Chequeo que el store no sea nulo y que exista en el maestro de tiendas.
                                string storeCode = fields["Store"];
                                if (!string.IsNullOrWhiteSpace(storeCode))
                                {
                                    store = Stores.Where(st => st.Code == storeCode).SingleOrDefault();
                                    if (store == null)
                                    {
                                        count++;
                                        importerResults.Add(new ImporterResult
                                        {
                                            Category = ResultCategory.TemporalTable,
                                            Description = string.Format(Errors.StoreCodeNotFoundInMaster, fields["Store"], row),
                                            ErrorType = ErrorType.Error,
                                            Id = count
                                        });
                                    }
                                }
                                else
                                {
                                    count++;
                                    importerResults.Add(new ImporterResult
                                    {
                                        Category = ResultCategory.TemporalTable,
                                        Description = string.Format(Errors.StoreCodeCantBeNull, row),
                                        ErrorType = ErrorType.Error,
                                        Id = count
                                    });
                                }

                                //Chequeo que el Article no sea nulo y que exista en el maestro de Articulos.
                                string articleEAN = fields["UPC"];
                                if (!string.IsNullOrWhiteSpace(articleEAN))
                                {
                                    article = Articles.Where(art => art.EAN == articleEAN).SingleOrDefault();
                                    if (article == null)
                                    {
                                        count++;
                                        importerResults.Add(new ImporterResult
                                        {
                                            Category = ResultCategory.TemporalTable,
                                            Description = string.Format(Errors.ArticleEanNotFoundInMaster, fields["UPC"], row),
                                            ErrorType = ErrorType.Error,
                                            Id = count
                                        });
                                    }
                                }
                                else
                                {
                                    count++;
                                    importerResults.Add(new ImporterResult
                                    {
                                        Category = ResultCategory.TemporalTable,
                                        Description = string.Format(Errors.ArticleEANCantBeNull, row),
                                        ErrorType = ErrorType.Error,
                                        Id = count
                                    });
                                }

                                //Parseo la fecha
                                string period = fields["cMonth"];
                                int year = int.Parse(period.Substring(0, 4));
                                int month = int.Parse(period.Substring(4, 2));
                                date = new DateTime(year, month, 1);

                                decimal units = decimal.Parse(fields["SKU_Quan"]);
                                decimal sales = decimal.Parse(fields["Sales"]);
                                decimal grossMargin = decimal.Parse(fields["Margin"]);
                                decimal grossSales = decimal.Parse(fields["Sales_Amount"]);
                                decimal price = units > 0 ? grossSales / units : 0;

                                //Agrego un registro de venta al DataTable.
                                if (article != null && store != null)
                                {
                                    DataRow datarow = sourceTable.NewRow();
                                    datarow["StoreId"] = store.Id;
                                    datarow["ArticleId"] = article.Id;
                                    datarow["Date"] = date;
                                    datarow["Units"] = units;
                                    datarow["Sales"] = sales;
                                    datarow["GM"] = grossMargin;
                                    datarow["GrossSales"] = grossSales;
                                    datarow["Price"] = price;

                                    sourceTable.Rows.Add(datarow);
                                }
                            }
                        }
                    }

                    // new method: SQLBulkCopy:
                    TempArticleSalesRepository.BulkCopy(sourceTable);
                }

            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.TemporalTable,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportArticleSalesStep3()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;
            try
            {
                //Verifico si hay tiendas sin Codigo o Nombre.
                List<TempArticleSaleRow> negativeMargins = TempArticleSalesRepository.Select(sale => sale.GM < 0);
                
                //TODO: Agregar aqui todas las validaciones necesarias para el Maestro de Tiendas
            }
            catch (Exception ex)
            {
                count++;
                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.Validation,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

        public IList<ImporterResult> ImportArticleSalesStep4()
        {
            IList<ImporterResult> importerResults = new List<ImporterResult>();
            int count = 0;

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    //Hago Update de Maestro de Tiendas
                    StoresRepository.UpdateFromTempStores(Country.Id);

                    //Hago Insert de Maestro Tiendas
                    StoresRepository.InsertFromTempStores(Country.Id);

                    scope.Complete();
                }

                //Borro las tablas temporales
                TempStoresRepository.TruncateTable();

                //Muevo Archivos importados a la carpeta old y Loggeo la importacion.
                string sourceDirectoryPath = ImporterHelper.GetStoreMasterFilePath(Country);
                ImporterHelper.MoveImportedFilesAndWriteLog(Country, sourceDirectoryPath);
            }
            catch (Exception ex)
            {
                count++;

                importerResults.Add(new ImporterResult
                {
                    Category = ResultCategory.Updating,
                    Description = ex.Message,
                    ErrorType = ErrorType.Error,
                    Id = count
                });
            }

            return importerResults;
        }

    }
}
